package com.example.securitydemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Package: com.example.securitydemo.config
 * @ClassName: MySecurityConfig
 * @Author: Think
 * @CreateTime: 2021/7/27 11:24
 * @Description:
 */
/*@EnableWebSecurity*/
public class AnotherSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("root").password(passwordEncoder().encode("root999")).authorities("user:add", "user:delete")
                .and()
                .withUser("zhang").password(passwordEncoder().encode("mm111")).authorities("user:delete");
    }

    /**
     * 对请求进行鉴权的配置
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 需要user:add权限才可以访问
                .antMatchers("/addUser").hasAuthority("user:add")
                // 需要user:delete权限才可以访问
                .antMatchers("/deleteUser").hasAuthority("user:delete")
                .and()
                .formLogin()
                .and()
                .csrf().disable();
    }

    /**
     * 默认开启密码加密，前端传入的密码Security会在加密后和数据库中的密文进行比对，一致的话就登录成功
     * 所以必须提供一个加密对象，供security加密前端明文密码使用
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
